package com.zl.net
{
	import flash.display.DisplayObject;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	
	import mx.controls.ProgressBar;
	import mx.core.Application;
	import mx.managers.PopUpManager;

	public class FileUploader extends EventDispatcher
	{
		public function FileUploader()
		{
			
		}
		
		protected var _url:String;
		protected var _fileFilterArray:Array = [];
		
		protected var _fileReference:FileReference;
		protected var _progressBar:ProgressBar;
		
		public function set url(s:String):void{
			_url = s;
		}
		
		public function chooseFile():void{
			if(_fileReference==null){
				_fileReference = new FileReference();
				_fileReference.addEventListener(Event.SELECT, onSelected);
				_fileReference.addEventListener(ProgressEvent.PROGRESS ,onUploading);
				_fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploaded);
				_fileReference.addEventListener(IOErrorEvent.IO_ERROR, onUploadFailed);
			}
			_fileReference.browse(_fileFilterArray);
		}
		
		protected function onSelected(e:Event):void{
			
		}
		protected function onUploading(e:ProgressEvent):void{
			var bytesTotal:uint = _fileReference.size;
			var percent:Number = (e.bytesLoaded / bytesTotal) * 100;
			_progressBar.setProgress(percent, 100);
			
			var percentStr:String = int(_progressBar.percentComplete) + "%";
			_progressBar.label = '已上传' + percentStr;
		}
		protected function onUploadFailed(e:IOErrorEvent):void{
			trace(e.toString());
			PopUpManager.removePopUp(_progressBar);
		}
		protected function onUploaded(e:DataEvent):void{
			PopUpManager.removePopUp(_progressBar);
		}
		
		public function uploadFile():void{
			if(!_fileReference || !_url){
				return;
			}else{
				_progressBar = getNewProgressBar();
				PopUpManager.addPopUp(_progressBar, Application.application as DisplayObject, true);
				PopUpManager.centerPopUp(_progressBar);
				
				_fileReference.upload(new URLRequest(_url));
			}
		}
		
		protected function getNewProgressBar():ProgressBar{
			var p:ProgressBar = new ProgressBar();
			p.width = 250;
			p.indeterminate = true;
			p.mode = 'manual';
			p.minimum = 0;
			p.maximum = 100;
			p.labelPlacement = "center";
			p.setStyle("barColor", "#E8E060");
			return p;		
		}
		
	}
}